package com.auicyh.demoapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.auicyh.tylb.comm.SerialHelper;
import com.auicyh.tylb.comm.SerialPort;
import com.auicyh.tylb.comm.SerialPortFinder;
import com.auicyh.tylb.constant.TabletMessage;
import com.auicyh.tylb.utils.DataConversion;
import com.auicyh.tylb.utils.EnCodeUtils;
import com.auicyh.tylb.utils.LogUtils;
import com.auicyh.tylb.utils.TylbException;

import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.Map;

/**
 * @author Ocean
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    /** 弱引用的Handler */
    private final MyHandler mHandler = new MyHandler(this);
    private SerialHelper mSerialHelper;
    /** 是否暂停线程(等待) */
    private volatile boolean isPause = false;
    private TextView mTextView;
    private SendCmdThread mSendCmdThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mTextView = findViewById(R.id.act_message);
        findViewById(R.id.act_more_cmd_bt).setOnClickListener(this);
        findViewById(R.id.fab).setOnClickListener(this);

        mSerialHelper = new SerialHelper(TabletMessage.PORT_ADDRESS_ROCKCHIP);
        mSerialHelper.setSerialPortListener(new SerialPortListener());


        try {
            String str = EnCodeUtils.enCode("赵海博", "8BFB9BA945A5F4582D85DBB22ACBEE65", "ocean12345");
            String s = EnCodeUtils.deCode(str, "8BFB9BA945A5F4582D85DBB22ACBEE65", "ocean12345");
            LogUtils.e(true, "密文" + str + "明文" + s);
        } catch (TylbException e) {
            e.printStackTrace();
            LogUtils.e(true, e.getMessage());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        // 单指令和多指令不能同时运行
        boolean open = mSerialHelper.isOpen();
        switch (v.getId()) {
            case R.id.act_more_cmd_bt:
                // 发送指令
                if (!open) {
                    try {
                        mSerialHelper.open();
                    } catch (TylbException e) {
                        LogUtils.e(true, e.getMessage());
                    }
                }
                if (!isPause) {
                    isPause = true;
                    mSendCmdThread = new SendCmdThread();
                    mSendCmdThread.setPriority(4);
                    mSendCmdThread.start();
                }
                break;


            default:

                break;
        }
    }


    /**
     * Handle
     * 1. 数据初始化完成的处理。
     * 2. 定位信息的处理。
     * 3. 蓝牙连接相关处理。
     */
    private static class MyHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;

        private MyHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final MainActivity hContext = mActivity.get();
            if (hContext != null) {
                switch (msg.what) {
                    case 9999:
                        // handle
                        break;

                    default:

                        break;
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSendCmdThread != null) {
            mSendCmdThread.interrupt();
        }
        if (mSerialHelper != null) {
            // 必须调用 onCancel 进行关闭
            mSerialHelper.onCancel();
        }
    }


    /**
     * 发送指令的线程
     */
    class SendCmdThread extends Thread {
        byte[] cmdPcbCodeArray = {0x01, 0x09, 0xa};


        @Override
        public void run() {
            super.run();
            while (isPause) {
                try {
                    sendCmd(cmdPcbCodeArray, "ID");
                } catch (TylbException e) {
                    LogUtils.e(true, e.getMessage());
                    isPause = false;
                } catch (InterruptedException e) {
                    LogUtils.e(true, "停止发送");
                    isPause = false;
                } catch (Exception e) {
                    isPause = false;
                    LogUtils.e(true, "停止");
                } finally {
                    mHandler.sendEmptyMessage(9999);
                }
            }
        }

        /**
         * 发送指令
         * @param cmdPcbCodeArray 指令集
         * @param sleep           睡眠时间
         * @throws TylbException        异常
         * @throws InterruptedException 休眠异常
         */
        private synchronized void sendCmd(byte[] cmdPcbCodeArray, String sleep) throws TylbException, InterruptedException {
            mSerialHelper.send(cmdPcbCodeArray);
            synchronized (MainActivity.this) {
                MainActivity.this.wait();
            }
        }
    }

    /**
     * 处理串口方法的数据
     */
    class SerialPortListener implements SerialHelper.SerialPortListener {

        @Override
        public void onWait(int count) {
            LogUtils.e(true, "结果 等待中" + count);
        }

        @Override
        public void onReceive(byte cmd, byte[] bytes, String hex, boolean check) {
            try {
                if (check) {
                    synchronized (MainActivity.this) {
                        MainActivity.this.notify();
                    }

                    onPcbData(cmd, bytes, hex);
                }
            } catch (TylbException e) {
                LogUtils.e(true, e.getMessage());
            }
        }

        @Override
        public void onFinish(int statCode) {
            LogUtils.e(true, "结果 结束" + statCode);
        }

        /**
         * PCB读到数的处理  处理数据
         *
         * @param bytes 返回的数组
         */
        private void onPcbData(byte cmd, byte[] bytes, String hex) throws TylbException {
            if (bytes == null) {
                throw new TylbException("数组为空", 91);
            }
            String hint;
            if (cmd == 0x06) {
                hint = "1 温度";
                // 电压
                double voltage = mSerialHelper.getVoltage(bytes, 8, 9);
                // 温度
                double temp = mSerialHelper.getTemp(bytes, 6, 7);
                String txt = "温度" + temp + "电压" + voltage;
                mTextView.setText(txt);
            } else if (cmd == 0x09) {
                String longCode = DataConversion.byteArrToHex(bytes, 2, 12);
                hint = "长编码" + longCode;
            } else if (cmd == 0x04) {
                hint = "电子秤";
                double newRealTimeValue = ((bytes[2] & 0xff) << 8) + (bytes[3] & 0xff);
                LogUtils.e(true, "电子秤" + newRealTimeValue + "\t\t" + hex);
            } else if (cmd == 0x01) {
                hint = "泵";
            } else {
                throw new TylbException("指令校验失败,没有当前指令" + cmd, 92);
            }
            LogUtils.e(true, "赵海博   " + hint + hex);
        }
    }
}

